package com.eland.oa.main.service;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.directwebremoting.annotations.RemoteMethod;
import org.directwebremoting.annotations.RemoteProxy;
import org.springframework.stereotype.Service;

import com.eland.oa.main.constant.ELOpCode;
import com.eland.oa.main.model.ELOpRtnPack;

@Service("main-service-login")
@RemoteProxy
public class LoginDEPService {
	
	public LoginDEPService() {
	}
	
	public boolean isUserLoggedIn() {
		try {
			Subject currentUser = SecurityUtils.getSubject();
			boolean isLoggedIn = currentUser.isAuthenticated();
			return isLoggedIn;
		} catch (Exception e) {
			return false;
		}
	}
	
	@RemoteMethod
	public ELOpRtnPack login(String userName, String password) {
		Subject currentUser = SecurityUtils.getSubject();
		AuthenticationToken token = new UsernamePasswordToken(userName, password);
		
		try {
			currentUser.login(token);
			return new ELOpRtnPack(ELOpCode.TYP_SUCCESS, 
					ELOpCode.OP_SYS_LOGIN, 
					ELOpCode.MSG_LOGIN_S_LOGIN_SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
			return new ELOpRtnPack(ELOpCode.TYP_ERROR, 
					ELOpCode.OP_SYS_LOGIN, 
					ELOpCode.MSG_LOGIN_E_INVALID_LOGIN);
		}
	}
}
